package org.atguigu.service.impl;

import org.atguigu.entity.TRole;
import org.atguigu.entity.TUser;
import org.atguigu.mapper.TRoleMapper;
import org.atguigu.mapper.TUserMapper;
import org.atguigu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    //逆向工程，根据数据库表生成mapper接口，mapper.xml，实体类
    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    private TRoleMapper tRoleMapper;

    /**
     * 该方法在security登录的时候调用
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询数据库数据
        TUser tUser = tUserMapper.selectByLoginAct(username);
        if (tUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        //查询当前用户的角色，并放入用户对象中
        List<TRole> tRoles = tRoleMapper.selectByUserId(tUser.getId());
        tUser.setTRoles(tRoles);
        return tUser;
    }
}
